
const Service = require('egg').Service;
const { Op } = require('sequelize');

class ProjectService extends Service {
  async findAll(payload) {
    const { ctx } = this;
    const { limit, offset, prop_order, order, name, collection } = payload;
    const where = payload.where;
    where[Op.or] = [
      { is_private: 0 },
      {
        '$member.id$': ctx.currentRequestData.userInfo.id,
      },
    ];
    const Order = [];
    const collectorRequired = collection ? parseInt(collection) === 1 : false;
    name ? (where.name = { [Op.like]: `%${name}%` }) : null;
    prop_order && order ? Order.push([prop_order, order]) : null;
    return await ctx.model.Projects.findAndCountAll({
      distinct: true,
      // limit,
      offset,
      where,
      order: Order,
      include: [
        {
          model: ctx.model.Users,
          attributes: ['username', 'id', 'avatar'],
          as: 'creator',
        },
        {
          model: ctx.model.Users,
          as: 'collector',
          where: {
            id: ctx.currentRequestData.userInfo.id,
          },
          required: collectorRequired,
        },
        {
          model: ctx.model.Users,
          as: 'member',
        },
      ],
    });
  }
}

module.exports = ProjectService;